<?php

include_once(INCLUDES . "Page.php");
include_once(INCLUDES . "Revision.php");
include_once(INCLUDES . "Content.php");

class SiteService {
	
	public function __construct() {
		$_SESSION["admin"] = true;
	}
	
	public function loadPages() {
		return Page::findAll(null, "lft");
	}
	
	public function createPage($page, $parentId = null, $title = "") {
		$page = Page::savePage($page, $parentId);
		$page->revisions[0]->addContent(new Content(array("field" => "title", "value" => $title)));
		$page = new Page($page->id);
		$page->loadRevisions(null, "created");
		return $page;
	}
	
	public function addPage(Page $page, $parentId = null) {
		return Page::savePage($page, $parentId);
	}
	
	public function editPage(Page $page) {
		return $page->save();
	}
	
	public function deletePage($pageId) {
		return Page::delete($pageId);
	}
	
	public function movePage($pageId, $newParentId = null, $prevPageId = null) {
		$page = new Page($pageId);
		Page::move($page, $newParentId, $prevPageId);
		return Page::findAll(array("lft BETWEEN ? AND ?", $page->lft, $page->rgt), "lft");
	}
	
	public function renamePage($pageId, $newName) {
		$page = new Page($pageId);
		Page::renamePage($page, $newName);
		return Page::findAll(array("lft BETWEEN ? AND ?", $page->lft, $page->rgt), "lft");
	}
	
	public function getRevisions($pageId) {
		return Revision::findAll(array("page_id = ?", $pageId), "created");
	}
	
	public function getContentsForRevision($revisionId) {
		return Content::findAll(array("revision_id = ?", $revisionId), "created");
	}
	
	public function savePage($pageId, $revisionId, $contents, $publish = false) {
		$page = new Page($pageId);
		$page->loadRevisions(array("id = ?", $revisionId));
		if (!count($page->revisions))
			return;
		
		$revision = $page->revisions[0];
		
		if ($contents) {
			foreach ($contents as $key => $value) {
				$content = new Content();
				$content->field = $value["name"];
				$content->value = $value["value"];
				$contents[$key] = $content;
			}
			$revision->contents = $contents;
			$revision->saveContents();
		}
		
		if ($publish && !$revision->publish) {
			$revision->publish = time();
			$newRevision = new Revision();
			$newRevision->templateId = $revision->templateId;
			$page->addRevision($newRevision);
			return array($revision, Revision::findFirst("page_id = $page->id", "created DESC"));
		}
	}
}

?>